#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <ctime>
#include "Thread.hpp"


const int NUM = 10;

using namespace std;

enum
{
    OK = 0,
    ERROR
};

class ThreadData
{
public:
    ThreadData(const string& name,int id,time_t createtime,int top)
        : _name(name),_id(id),_createTime(createtime)
        ,_status(OK),_top(top)
    {
        
    }

    ~ThreadData()
    {

    }

    string _name;
    int _id;
    uint64_t _createTime;

    int _status;
    int _top;
    int _result;
};

void* thread_run(void* args)
{
    // char* name = (char*)args;
    ThreadData* td = static_cast<ThreadData*>(args);
    for(int i = 0;i<td->_top;i++)
    {
        td->_result+=i;
    }

    pthread_exit(td);


    
    // while(true)
    // {
    //     cout << "new-thread running,my name is " 
    //     << td->_name << " "
    //     << td->_id << " "
    //     << td->_createTime << " "
    //     << endl;
    //     sleep(1);
    //     break;
    // }
    // delete td;
    // pthread_exit((void*)1);

    // return nullptr;
}



int main()
{
    // 1
    // pthread_t t;
    // pthread_create(&t,nullptr,thread_run,nullptr);



    // 2
    pthread_t tid[NUM];
    for(int i = 0;i<10;i++)
    {
        char tname[64];
        //char* tname = new char[64];

        // snprintf(tname,sizeof(tname),"thread-%d",i+1);
        snprintf(tname,64,"thread-%d",i+1);

        ThreadData * td = new ThreadData(tname,i+1,time(nullptr),100+i);
        pthread_create(tid+i,nullptr,thread_run,td);
    }

    // 3
    void* ret = nullptr;
    for(int i = 0;i<10;i++)
    {
        int n = pthread_join(tid[i],&ret);
        if(n != 0)
        {
            cerr << "error" << endl;
        }

        ThreadData* td = static_cast<ThreadData*>(ret);
        cout << "quit result :"<< td->_result << endl;
    }
    cout << "all thread quit" << endl;

    // while(true)
    // {
    //     cout << "main running; new thread id->"  << endl;
    //     sleep(1);
    // }
    return 0;
}
